package com.fy56.platform.goodsTracking.commons.security;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class ReadFileTool {

	public static void readFileByBytes(String fileName){
		   File file = new File(fileName);
		   InputStream in = null;
		   try {
		    System.out.println("以字节为单位读取文件内容，一次读一个字节：");
		    // 一次读一个字节
		    in = new FileInputStream(file);
		    int tempbyte;
		    while((tempbyte=in.read()) != -1){
		     System.out.write(tempbyte);
		    }
		    in.close();
		   } catch (IOException e) {
		    e.printStackTrace();
		    return;
		   }
		   try {
		    System.out.println("以字节为单位读取文件内容，一次读多个字节：");
		    //一次读多个字节
		    byte[] tempbytes = new byte[100];
		    int byteread = 0;
		    in = new FileInputStream(fileName);
		    ReadFileTool.showAvailableBytes(in);
		    //读入多个字节到字节数组中，byteread为一次读入的字节数
		    while ((byteread = in.read(tempbytes)) != -1){
		     System.out.write(tempbytes, 0, byteread);
		    }
		   } catch (Exception e1) {
		    e1.printStackTrace();
		   } finally {
		    if (in != null){
		     try {
		      in.close();
		     } catch (IOException e1) {
		     }
		    }
		   }
		}

	/**
	   * 显示输入流中还剩的字节数
	   * @param in
	   */
	private static void showAvailableBytes(InputStream in){
	   try {
	    System.out.println("当前字节输入流中的字节数为:" + in.available());
	   } catch (IOException e) {
	    e.printStackTrace();
	   }
	}
	
	public static byte[] readfileByBytes(String filename) {
		
		int size = 0;
		byte[] echoBuf =null;
		FileInputStream in=null;
		FileChannel channel=null;
		//装载一个索引文件到buffer
		try {
			Thread.sleep(5);
			in = new FileInputStream(filename);
			channel = in.getChannel();
			MappedByteBuffer buffer = channel.map(
					FileChannel.MapMode.READ_ONLY, 0, (int) channel.size());
			size = (int) channel.size();
			echoBuf = new byte[size];
			buffer.get(echoBuf);
			buffer.clear();
			buffer = null;
			channel.close();
			in.close();
			
		} catch (Exception ex) {
			try
			{
				if(in!=null)
				{
					in.close();
					in=null;
				}
				if(channel!=null)
				{
					channel.close();
					channel=null;
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			//System.out.println("");
		}
		return echoBuf;
	}

} 
 
